package com.hainatong.mvvmbase.base;

import androidx.core.content.ContextCompat;

import com.hainatong.mvvmbase.R;
import com.hainatong.mvvmbase.application.RootApplication;
import com.hainatong.mvvmbase.loadsir.callback.Callback;
import com.hainatong.mvvmbase.loadsir.core.LoadService;
import com.hainatong.mvvmbase.loadsir.core.LoadSir;
import com.hainatong.mvvmbase.loadsir.layoutcallback.EmptyCallback;
import com.hainatong.mvvmbase.loadsir.layoutcallback.ErrorCallback;
import com.hainatong.mvvmbase.loadsir.layoutcallback.LoadingCallback;
import com.hainatong.mvvmbase.utils.ClassUtil;
import com.hainatong.mvvmbase.utils.L;
import com.hainatong.mvvmbase.utils.ScreenAutoAdapter;
import com.hainatong.mvvmbase.utils.StatusBarUtils;

import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.ViewModelProvider;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public abstract class BaseMvvmActivity<V extends ViewDataBinding, VM extends AndroidViewModel> extends AppCompatActivity {
    public static String TAG = BaseMvvmActivity.class.getSimpleName();

    protected VM viewModel;

    protected V viewDataBinding;

    //RxBus  取消订阅 关系时  使用
    private CompositeDisposable mCompositeDisposable;

    protected LoadService mLoadService;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (((RootApplication) RootApplication.getInstance()).isScreenAuto()) {
            ScreenAutoAdapter.match(this, ((RootApplication) RootApplication.getInstance()).getDESIGN_SIZE());
        }

        super.onCreate(savedInstanceState);

        initStatusBar();
        initViewModel();
        performDataBinding();

        setContentView(viewDataBinding.getRoot());

        initView();
        initData();
    }

    protected void initStatusBar() {
        // 设置透明状态栏，兼容4.4
        // 设置状态栏为白底黑字
        StatusBarUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.toolbar_bg));
        StatusBarUtils.setStatusBarDarkFont(this, true);

    }

    private void initViewModel() {
        Class<VM> viewModelClass = ClassUtil.getViewModel(this);
        if (viewModelClass != null) {
            viewModel = new ViewModelProvider(this).get(viewModelClass);
        }
    }

    private void performDataBinding() {

        viewDataBinding = DataBindingUtil.setContentView(this, getLayoutId());

        if (getBindingVariable() > 0) {
            viewDataBinding.setVariable(getBindingVariable(), viewModel);
        }
        viewDataBinding.executePendingBindings();

    }

    @LayoutRes
    protected abstract int getLayoutId();

    /**
     * 获取参数Variable
     */
    protected abstract int getBindingVariable();


    /**
     * 注册LoadSir
     *
     * @param view 替换视图
     */
    public void setLoadSir(Object view) {
        if (mLoadService == null) {
            mLoadService = LoadSir.getDefault()
                    .register(view, (Callback.OnReloadListener) v -> onRetryBtnClick());
        }
    }

    private boolean isShowedContent = false;

    public void showContent() {
        if (null != mLoadService) {
            isShowedContent = true;
            mLoadService.showSuccess();
        }
    }


    public void showLoading() {
        if (null != mLoadService) {
            L.e("showLoading", "showLoading()");
            mLoadService.showCallback(LoadingCallback.class);
        }
    }


    public void showEmpty() {
        if (null != mLoadService) {
            mLoadService.showCallback(EmptyCallback.class);
        }
    }


    public void showFailure(String message) {
        if (null != mLoadService) {
            if (!isShowedContent) {
                mLoadService.showCallback(ErrorCallback.class);
            } else {
                //Toast.show(this, message);
            }
        }
    }


    protected abstract void initView();

    protected abstract void initData();


    /**
     * 失败重试,重新加载事件
     */
    protected abstract void onRetryBtnClick();

    /**
     * 设置titlebar
     */
    protected void setToolBar(Toolbar toolbar) {
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //去除toolbar 返回键
            actionBar.setDisplayHomeAsUpEnabled(false);
            // 显示 toolbar内容
            actionBar.setDisplayShowCustomEnabled(true);
        }

        // 这里 简单处理一下 toolbar  不用actionbar的特性

        /*
        if (actionBar != null)
        {
            //去除默认Title显示
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.svg_back);
        }
        toolbar.setNavigationOnClickListener(view -> {
            supportFinishAfterTransition();
        });
        */
    }

    protected void setTitle(String title) {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //去除默认Title显示
            actionBar.setDisplayShowTitleEnabled(true);
            actionBar.setTitle(title);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1) {
            getResources();
        }
    }

    /**
     * 禁止改变字体大小
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    public void addSubscription(Disposable s) {
        if (this.mCompositeDisposable == null) {
            this.mCompositeDisposable = new CompositeDisposable();
        }
        this.mCompositeDisposable.add(s);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (this.mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            // clear 和 dispose的区别是：  disposed = true;
            this.mCompositeDisposable.clear();
        }
    }

    public void removeDisposable() {
        if (this.mCompositeDisposable != null && !mCompositeDisposable.isDisposed()) {
            this.mCompositeDisposable.dispose();
        }
    }
}
